import { delete_role, role_list, role_status } from '@/services/role';
import paging_fun from '@/utils/paging';
import { InfoCircleTwoTone, PlusOutlined } from '@ant-design/icons';
import { ActionType, PageContainer, ProColumns, ProTable } from '@ant-design/pro-components';
import { Button, Divider, message, Modal, Switch } from 'antd';
import { useRef, useState } from 'react';
import AddRolePermission from './components/AddRolePermission';
import EditRolePermission from './components/EditRolePermission';
import SetPermission from './components/SetPermission';
type GithubIssueItem = {
  id: number;
  rolename: string;
  user_count: string;
  manage_name: string;
  created_at: string;
  status: number;
};
const RolePermission = () => {
  const actionRef = useRef<ActionType>();
  // 存储当前id
  const [editId, seteditId] = useState<number>();
  // 控制新建角色模态框的状态
  const [isAddModalOpen, setIsAddModalOpen] = useState(false);
  // 控制设置权限模态框的状态
  const [isSetModalOpen, setIsSetModalOpen] = useState(false);
  // 控制查看/编辑角色模态框的状态
  const [isEditRoleModalOpen, setIsEditRoleModalOpen] = useState(false);
  // 控制是查看还是编辑的模态框 check是查看 edit是编辑
  const [flag, setFlag] = useState('')
  // 控制删除模态框的状态
  const [delVisible, setDelVisible] = useState(false);
  // 控制新建角色模态框显示和隐藏
  const isShowAddModal = (show: boolean) => {
    setIsAddModalOpen(show);
  };
  // 控制设置权限模态框显示和隐藏
  const isShowSetModal = (show: boolean) => {
    setIsSetModalOpen(show);
  };
  // 控制编辑角色模态框显示和隐藏
  const isShowEditRoleModal = (show: boolean) => {
    setIsEditRoleModalOpen(show);
  };
  // 获取角色列表
  const get_role_list = async (params: {
    pageSize?: number | undefined;
    current?: number | undefined;
    keyword?: string | undefined;
  }) => {
    let request_body = {
      ...params,
      current: params.current,
      pageSize: params.pageSize,
    };
    let res = await role_list(request_body);
    // console.log('角色', res);
    return {
      data: res.data.list,
      success: true,
      total: res.data.total_count,
    };
  };
  // 启用/禁用角色
  const edit_rolestatus = async (id: number, status: boolean) => {
    let request_body = {
      id,
      status: status ? 1 : 0,
    };
    const res: any = await role_status(request_body);
    if (res.code == 200) {
      if (status) {
        message.success('角色启用成功！');
      } else {
        message.success('角色禁用成功！');
      }
      actionRef.current?.reload();
    } else {
      message.error(res.msg);
    }
  };
  // 删除按钮回调
  const isShowDelVisible = (
    status: boolean | ((prevState: boolean) => boolean),
    editId?: number,
  ) => {
    setDelVisible(status);
    seteditId(editId);
  };
  // 确认删除角色的回调
  const delOk = async () => {
    let request_body = {
      id: editId,
    };
    const res: any = await delete_role(request_body);
    if (res.msg == 'ok') {
      message.success('删除成功');
      actionRef.current?.reload();
      paging_fun(actionRef);
    } else {
      message.error(res.msg);
    }
    setDelVisible(false);
  };
  // 角色列表字段
  const columns: ProColumns<GithubIssueItem>[] = [
    {
      title: '序号',
      dataIndex: 'index',
      hideInSearch: true,
      valueType: 'index',
      align: 'center',
    },
    {
      title: '角色名称',
      dataIndex: 'rolename',
      align: 'center',
    },
    {
      title: '角色人数',
      dataIndex: 'user_count',
      hideInSearch: true,
      align: 'center',
    },
    {
      title: '创建人',
      dataIndex: 'manage_name',
      hideInSearch: true,
      align: 'center',
    },
    {
      title: '创建时间',
      dataIndex: 'create_time',
      hideInSearch: true,
      align: 'center',
    },
    {
      title: '状态',
      dataIndex: 'status',
      align: 'center',
      valueEnum: {
        0: {
          text: '禁用',
        },
        1: {
          text: '启用',
        },
      },
      render: (_, record) => (
        <Switch
          key={record.status === 1}
          checkedChildren="启用"
          unCheckedChildren="禁用"
          checked={record.status === 1}
          onChange={(event: boolean) => {
            edit_rolestatus(record.id, event);
          }}
        />
      ),
    },
    {
      title: '操作',
      hideInSearch: true,
      key: 'action',
      align: 'center',
      render: (_, record) => [
        <Button
          key="Role"
          type="link"
          onClick={() => {
            seteditId(record.id);
            isShowSetModal(true);
          }}
          disabled={record.status === 1}
        >
          设置权限
        </Button>,
        <Button
          key="check"
          type="link"
          onClick={() => {
            seteditId(record.id);
            setFlag('check');
            isShowEditRoleModal(true);
          }}
        // disabled={record.status === 1}
        >
          查看权限
        </Button>,
        <Button
          key="Editor"
          type="link"
          onClick={() => {
            seteditId(record.id);
            setFlag('edit')
            isShowEditRoleModal(true);
          }}
          disabled={record.status === 1}
        >
          编辑
        </Button>,
        <Button
          key="Del"
          type="link"
          onClick={() => {
            isShowDelVisible(true, record.id);
          }}
          disabled={record.status === 1}
        >
          删除
        </Button>,
      ],
    },
  ];

  return (
    <PageContainer breadcrumb={false}>
      <ProTable<GithubIssueItem>
        columns={columns}
        actionRef={actionRef}
        cardBordered
        request={async (params = {}) => get_role_list(params)}
        editable={{
          type: 'multiple',
        }}
        rowKey={(record) => record.id}
        search={{
          labelWidth: 'auto',
          collapseRender: false,
          collapsed: false,
          span: 6,
        }}
        options={{
          setting: {
            listsHeight: 400,
          },
        }}
        pagination={{
          pageSize: 10,
        }}
        dateFormatter="string"
        headerTitle="角色列表"
        toolBarRender={() => [
          <Button
            key="button"
            icon={<PlusOutlined />}
            type="primary"
            onClick={() => isShowAddModal(true)}
          >
            新建
          </Button>,
        ]}
      />
      {/* 新增角色 */}
      {isAddModalOpen ? (
        <AddRolePermission
          isAddModalOpen={isAddModalOpen}
          isShowAddModal={isShowAddModal}
          actionRef={actionRef}
        ></AddRolePermission>
      ) : (
        ''
      )}
      {/* 设置权限 */}
      {isSetModalOpen ? (
        <SetPermission
          isSetModalOpen={isSetModalOpen}
          isShowSetModal={isShowSetModal}
          actionRef={actionRef}
          editId={editId}
        ></SetPermission>
      ) : (
        ''
      )}
      {/* 查看/编辑角色 */}
      {isEditRoleModalOpen ? (
        <EditRolePermission
          isEditRoleModalOpen={isEditRoleModalOpen}
          isShowEditRoleModal={isShowEditRoleModal}
          actionRef={actionRef}
          editId={editId}
          flag={flag}
        ></EditRolePermission>
      ) : (
        ''
      )}
      <Modal
        title="删除确认"
        open={delVisible}
        onOk={delOk}
        onCancel={() => isShowDelVisible(false)}
      >
        <Divider />
        <p>
          <InfoCircleTwoTone twoToneColor="#ffcc00" /> 角色信息删除后无法恢复，确定要删除吗？
        </p>
      </Modal>
    </PageContainer>
  );
};
export default RolePermission;
